package org.intellij.doctree;

import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.intellij.doctree.node.*;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

import javax.swing.tree.TreeModel;

public class ApplicationDocs implements ApplicationComponent, JDOMExternalizable, DocTreeComponent {

    public static final String ACTION_PLACE = "AppDocTreeActionPlace";
    public static final String COMPONENT_NAME = "org.intellij.doctree.ApplicationDocs";

    private static boolean readStoredNodes = false;

    private DocTreeModel appTreeModel = new DocTreeModel(FolderNode.APPLICATION_ROOT);

    public ApplicationDocs() {
    }

    public void initComponent() {
        if (!readStoredNodes)
            XMLHelper.readDefaultDocuments(appTreeModel);
    }

    public void disposeComponent() {
        //Do nothing
    }

    @NotNull
    public String getComponentName() {
        return COMPONENT_NAME;
    }

    public void readExternal(Element element) throws InvalidDataException {
        XMLHelper.readDocuments(element, appTreeModel);
        readStoredNodes = true;
    }

    public void writeExternal(Element element) throws WriteExternalException {
        XMLHelper.writeDocuments(element, appTreeModel);
    }

    public TreeModel getTreeModel() {
        return appTreeModel;
    }

    public void addFolder(FolderNode parent, Folder newFolder) {
        appTreeModel.insertNodeInto(new FolderNode(newFolder), parent, parent.getChildCount());
    }

    public void addDocument(FolderNode parent, Document newDocument) {
        appTreeModel.insertNodeInto(new DocumentNode(newDocument), parent, parent.getChildCount());
    }

    public void updateNode(FolderNode originalNode, Folder folder) {
        originalNode.setFolder(folder);
        appTreeModel.nodeChanged(originalNode);
    }

    public void updateNode(DocumentNode originalNode, Document document) {
        originalNode.setDocument(document);
        appTreeModel.nodeChanged(originalNode);
    }

    public void removeNode(DocTreeNode node) {
        appTreeModel.removeNodeFromParent(node);
    }

    public void moveNodeUp(DocTreeNode node) {
        appTreeModel.moveNodeUp(node);
    }

    public void moveNodeDown(DocTreeNode node) {
        appTreeModel.moveNodeDown(node);
    }

}
